<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/10/16 11:10
 * Desc: 美食
 */
trait Trait_Api_Food
{
    /**
     * 首页属性
     * @param $params
     * @return array
     */
    public function index_attr($params = array())
    {
        /**
         * @var $dest_id
         * @var $row
         */
        extract($params);

        $parent_builder = DB::select()
            ->from('food_category')
            ->where('pid', '=', 0)
            ->and_where('isopen', '=', 1);
        if (!empty($dest_id)) {
            $parent_builder->and_where(DB::expr(' AND  FIND_IN_SET(' . $dest_id . ',destid) '));
        }
        $list = $parent_builder->order_by(DB::expr("IFNULL(displayorder,9999)"), 'ASC')
            ->limit(8)
            ->execute()
            ->as_array();
        foreach ($list as &$item) {
            $item['litpic'] = $this->img_url($item['litpic']);
        }
        return array('list' => $list);
    }

    /**
     * 获取套餐详情
     * @param $params
     * @return array|mixed
     * @throws Exception
     */
    public function get_suit_detail($params)
    {
        /**
         * @var $mid
         * @var $suit_id
         * @var $together_id
         */
        extract($params);

        $mid = !empty($mid) ? $mid : null;
        if (!empty($together_id)) {
            $suit = Model_Api_V2_Together::suit($together_id, $mid);
        } else {
            $suit = Model_Api_V2_Food::suit_by_id($suit_id);
        }

        if (empty($suit)) {
            throw new Exception('套餐不存在');
        }
        if(isset($suit['err_msg'])){
            throw new Exception($suit['err_msg']);
        }

        // 支付方式
        $suit['paytype_name'] = Model_Member_Order::get_paytype_name(1);

        // 预订确认方式名称
        $suit['confirm_type_name'] = Model_Product::get_confirm_type_name($suit['is_confirm_pay']);

        // 格式化退款规则
        $refund_class = Service_Refund_Rule_Factory::get_instance(self::TYPE_ID);
        $suit['refund_restriction_name'] = $refund_class->get_refund_restriction_name($suit['refund_restriction']);

        //  查询产品信息
        $product = DB::select('title')->from('food')->where('id', '=', $suit['productid'])->execute()->current();
        $suit['product_title'] = $product['title'];

        unset($suit['dishes']);
        $suit['price'] = Currency_Tool::price($suit['price']);

        return $suit;
    }

    /**
     * 添加折扣订单
     * @param $params
     * @return array
     * @throws Exception
     * @throws Kohana_Exception
     */
    public function add_discount_order($params)
    {
        $mid         = $params['mid'];
        $member_info = $params['member_info'];
        $product_id  = $params['product_id'];

        //消费总金额
        $consume_total = $params['consume_total'];

        //不参与优惠金额
        $discount_total = $params['discount_total'];
        if ($discount_total > $consume_total) {
            throw new Exception('不参与优惠金额必须小于订单金额');
        }

        //产品信息
        $info = DB::select()
            ->from('food')
            ->where('id', '=', $product_id)
            ->and_where('ishidden', '=', 0)
            ->execute()
            ->current();

        //下架状态判断
        if ($info['status'] != 3) {
            throw new Exception('当前产品已下架');
        }

        //判断买单是否已经开启
        if ($info['maidan_status'] != 1) {
            throw new Exception('当前产品不支持买单');
        }

        $pay_discount     = $info['pay_discount'];
        $pay_discount_dec = sprintf("%.4f", $pay_discount / 10);
        $pay_start        = $info['pay_start'];
        $pay_end          = $info['pay_end'];
        $pay_start        = strtotime(date('Y-m-d') . ' ' . $pay_start);
        $pay_end          = strtotime(date('Y-m-d') . ' ' . $pay_end);

        //判断买单时间
        if (!$pay_start || !$pay_end) {
            throw new Exception('当前产品不支持买单');
        }
        if ($pay_start > time()) {
            throw new Exception('买单时间还未到');
        }
        if (time() > $pay_end) {
            throw new Exception('买单时间已结束');
        }

        //打折优惠
        $zhe_kou_amount = ($consume_total - $discount_total) * (1 - $pay_discount_dec);
        $zhe_kou_amount = sprintf("%.2f", $zhe_kou_amount);
        $pay_amount     = $consume_total + $discount_total - $zhe_kou_amount;
        if ($pay_amount <= 0) {
            throw new Exception('支付金额错误');
        }

        $linkman = $member_info['nickname'];
        $linktel = $member_info['mobile'];

        // 备注信息
        $discount_total = sprintf("%.2f", $discount_total);
        $consume_total = sprintf("%.2f", $consume_total);
        $remark = "买单打折{$pay_discount}折，打折优惠【{$zhe_kou_amount}】不参与打折金额【{$discount_total}】，订单总金额【{$consume_total}】";

        //积分评论
        $jifencomment_info = Model_Jifen::get_used_jifencomment(self::TYPE_ID);
        $jifencomment      = empty($jifencomment_info) ? 0 : $jifencomment_info['value'];

        // 订单编号
        $ordersn = Product::get_ordersn(self::TYPE_ID);

        $source = Arr::get($params, 'source', 3);
        // 订单数据
        $order = array(
            'ordersn' => $ordersn,
            'litpic' => $info['litpic'],
            'typeid' => self::TYPE_ID,
            'productautoid' => $product_id,
            'productaid' => $info['aid'],
            'productname' => $info['title'],
            'departdate' => '',
            'webid' => 0,
            'addtime' => time(),
            'linkman' => $linkman,
            'linktel' => $linktel,
            'linkemail' => '',
            'remark' => $remark,
            'usejifen' => 0,
            'needjifen' => 0,
            'jifentprice' => 0,
            'jifenbook' => $info['jifenbook_id'],
            'jifencomment' => $jifencomment,
            'memberid' => $mid,
            'suitid' => 0,
            'discount_total' => $discount_total,//不参与优惠的金额
            'platform_discount' => $zhe_kou_amount,//打折优惠
            'source' => $source,//订单来源
            'price' => $consume_total,//消费总金额
            'dingnum' => 1,//成人数量
            'childnum' => 0,//小孩数量
            'oldnum' => 0,//老人数量
            'people4_num' => 0,//人群4
            'people5_num' => 0,//人群5
            'people6_num' => 0,//人群6
            'status' => 1,//订单状态
            'paytype' => 1,//支付方式
            'pay_way' => 1,//支付方式
            'dingjin' => 0,//订金
            'childprice' => 0,//小孩价格
            'oldprice' => 0,//老人价格
            'people4_price' => 0,//人群4价格
            'people5_price' => 0,//人群5价格
            'people6_price' => 0,//人群6价格
            'roombalance' => 0,//客房余额
            'suit_name' => '',
            'refund_restriction' => 1,
            'auto_close_time' => 3600 + time(),
        );

        // 保存订单
        $out = Model_Api_V2_Order::add_order($order, 'Model_Food');
        if (!$out['status']) {
            throw new Exception($out['msg']);
        }

        $order_info                 = Model_Member_Order::order_info($order['ordersn']);
        $order_info['orderid']      = $order_info['id'];
        $order_info['need_confirm'] = 0;

        //订单结算信息表数据更新
        Model_Member_Order_Compute::update($order['ordersn']);

        Hook::trigger('order_created', $order);

        $filter_keys = array('id', 'orderid', 'ordersn', 'pageType', 'typeid', 'status');
        return $this->filter_data($filter_keys, $order_info);
    }



    /**
     * 属性筛选条件
     * @return array
     */
    public function attribute_filter()
    {
        $data = $this->get_attribute_by_pid();
        foreach ($data as &$item) {
            $item['child'] = $this->get_attribute_by_pid($item['id']);
        }
        return $data;
    }

    /**
     * 按pid获取属性
     * @param $pid
     * @return array
     */
    public function get_attribute_by_pid($pid = 0)
    {
        return DB::select('id', array('attrname', 'name'))
            ->from('food_attr')
            ->where('pid', '=', $pid)
            ->and_where('isopen', '=', 1)
            ->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')
            ->execute()
            ->as_array();
    }
}